package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.config.FasrDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.config.FastdfsConfig;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FasrDFSClientUtil fasrDFSClientUtil;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.检查参数
        if(multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String file="";
        try {
            file = fasrDFSClientUtil.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(file);
        wmMaterial.setIsCollection((short)0);

        WmUser user= WmThreadLocalUtils.getUser();  //从本地线程获取用户id
        wmMaterial.setUserId(user.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        wmMaterial.setUrl(fileServerUrl+file);

        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto.getIsCollection()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();//

        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<>();
        Integer userId = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId,userId);

        if (dto.getIsCollection()!=null && dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //select * from wmmaterial w where w.user_id=? and w.is_collection=? order by create_time desc;

        IPage pageparam = new Page(dto.getPage(), dto.getSize());
        IPage iPage = page(pageparam, wrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        List<WmMaterial> list=iPage.getRecords();
        list=list.stream().map(a->{a.setUrl(fileServerUrl+a.getUrl()); return  a;}).collect(Collectors.toList());//jdk1.8 stream流  遍历集合

        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id 查看引用库中是否存在
        QueryWrapper<WmNewsMaterial> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            return ResponseResult.okResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //删除fastdfs图片
        WmMaterial wmMaterial = getById(id);
        fasrDFSClientUtil.delFile(wmMaterial.getUrl().replaceAll(" ",""));

        //根据id删除媒体库资源
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        QueryWrapper<WmMaterial> wrapper = new QueryWrapper<>();
//        全部收藏与取消
//        wrapper.lambda().eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,uid);
//        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type));
        //单个收藏与取消
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
